
// 后端路由数据
const data = [
    {
        id: 1,
        name: 'Permission',
        title: '权限管理',
        path: '/permission',
        redirect: '/permission/user',
        icon: 'permission',
        hidden: false,
        pid: 0
    },
    {
        id: 2,
        name: 'User',
        title: '用户列表',
        path: 'user',
        redirect: '',
        icon: 'User',
        hidden: false,
        pid: 1
    },
    {
        id: 3,
        name: 'Role',
        title: '角色列表',
        path: 'role',
        redirect: '',
        icon: 'role',
        hidden: false,
        pid: 1
    },
    {
        id: 4,
        name: 'Menu',
        title: '菜单列表',
        path: 'menu',
        redirect: '',
        icon: 'menu',
        hidden: true,
        pid: 1
    },

    {
        id: 5,
        name: 'Product',
        title: '商品',
        path: '/product',
        redirect: '',
        icon: 'product',
        hidden: true,
        pid: 0
    },
    {
        id: 6,
        name: 'ProductList',
        title: '商品列表',
        path: 'product-list',
        redirect: '',
        icon: 'product',
        hidden: true,
        pid: 5
    },
    {
        id: 7,
        name: 'ProducTCategary',
        title: '商品分类',
        path: 'product-categary',
        redirect: '',
        icon: 'categary',
        hidden: false,
        pid: 5
    },
    {
        id: 8,
        name: 'ProductAttribute',
        title: '产品分类',
        path: 'product-attribute',
        redirect: '',
        icon: 'attribute',
        hidden: false,
        pid: 5
    },
    {
        id: 9,
        name: 'ProductAttributeChild',
        title: '子分类',
        path: 'product-attribute-child',
        redirect: '',
        icon: 'attribute',
        hidden: false,
        pid: 8
    },
]


function formatDataToTree(data) {
    const parents = data.filter(c => c.pid === 0)
    const children = data.filter(c => c.pid !== 0)
    recursive(parents, children)

    function recursive(parents, children) {
        parents.forEach(p => {
            children.forEach((c,i) => {
                if (c.pid === p.id) {
                    let _c = JSON.parse(JSON.stringify(children))
                    _c.splice(i, 1)
                    recursive([c], _c)

                    if (p.children) {
                        p.children.push(c)
                    } else {
                        p.children = [c]
                    }
                }
            })
        })
    }
    return parents
}

const treeData = formatDataToTree(data)
// console.log('treeData', treeData)

function generateRouter(userRoutes) {
    let newRouters = userRoutes.map((r) => {
        let route = Object.assign({}, r, {
            component: () => import(`@/views/${r.name}`)
        })

        if (r.children) {
            route.children = generateRouter(r.children)
        }

        return route
    })
    return newRouters
}

const userRoutes = generateRouter(treeData)

console.log('userRoutes', userRoutes)